import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { NavBar, Tabs, Card, Selector, Button, Toast } from 'antd-mobile';
import { LeftOutline } from 'antd-mobile-icons';
import styles from './GradeQuery.module.css';

function GradeQuery() {
  const navigate = useNavigate();
  const [selectedSemester, setSelectedSemester] = useState(['2023-2024-2']);

  const handleBack = () => {
    navigate(-1);
  };

  // 学期选项
  const semesterOptions = [
    { label: '2023-2024学年第二学期', value: '2023-2024-2' },
    { label: '2023-2024学年第一学期', value: '2023-2024-1' },
    { label: '2022-2023学年第二学期', value: '2022-2023-2' },
    { label: '2022-2023学年第一学期', value: '2022-2023-1' },
  ];

  // 模拟成绩数据
  const gradesData = {
    '2023-2024-2': [
      {
        id: 1,
        courseName: '高等数学A(2)',
        courseCode: 'MATH2001',
        credit: 5.0,
        score: 92,
        gradePoint: 4.2,
        courseType: '必修课',
        teacher: '张教授',
        status: '已录入'
      },
      {
        id: 2,
        courseName: '大学物理B(2)',
        courseCode: 'PHYS2002',
        credit: 4.0,
        score: 88,
        gradePoint: 3.8,
        courseType: '必修课',
        teacher: '李教授',
        status: '已录入'
      },
      {
        id: 3,
        courseName: '数据结构与算法',
        courseCode: 'CS2003',
        credit: 3.0,
        score: 95,
        gradePoint: 4.5,
        courseType: '专业课',
        teacher: '王教授',
        status: '已录入'
      },
      {
        id: 4,
        courseName: '英语听说(2)',
        courseCode: 'ENG2004',
        credit: 2.0,
        score: 85,
        gradePoint: 3.5,
        courseType: '必修课',
        teacher: '刘老师',
        status: '已录入'
      },
      {
        id: 5,
        courseName: '体育(2)',
        courseCode: 'PE2005',
        credit: 1.0,
        score: 90,
        gradePoint: 4.0,
        courseType: '必修课',
        teacher: '陈老师',
        status: '已录入'
      }
    ]
  };

  // 计算统计信息
  const calculateStats = (grades) => {
    if (!grades || grades.length === 0) return { totalCredits: 0, gpa: 0, averageScore: 0 };
    
    const totalCredits = grades.reduce((sum, grade) => sum + grade.credit, 0);
    const totalGradePoints = grades.reduce((sum, grade) => sum + (grade.gradePoint * grade.credit), 0);
    const totalScores = grades.reduce((sum, grade) => sum + grade.score, 0);
    
    return {
      totalCredits: totalCredits.toFixed(1),
      gpa: (totalGradePoints / totalCredits).toFixed(2),
      averageScore: (totalScores / grades.length).toFixed(1)
    };
  };

  const currentGrades = gradesData[selectedSemester[0]] || [];
  const stats = calculateStats(currentGrades);

  const getScoreColor = (score) => {
    if (score >= 90) return '#52c41a';
    if (score >= 80) return '#1890ff';
    if (score >= 70) return '#fa8c16';
    if (score >= 60) return '#faad14';
    return '#ff4d4f';
  };

  const getGradeLevel = (score) => {
    if (score >= 90) return '优秀';
    if (score >= 80) return '良好';
    if (score >= 70) return '中等';
    if (score >= 60) return '及格';
    return '不及格';
  };

  const handleExport = () => {
    Toast.show({
      content: '成绩单导出功能开发中...',
      position: 'center',
    });
  };

  return (
    <div className={styles.container}>
      {/* 导航栏 */}
      <NavBar 
        onBack={handleBack}
        backIcon={<LeftOutline />}
        className={styles.navbar}
      >
        成绩查询
      </NavBar>

      {/* 主要内容 */}
      <div className={styles.content}>
        {/* 学期选择 */}
        <Card className={styles.selectorCard}>
          <div className={styles.selectorHeader}>
            <h3 className={styles.selectorTitle}>选择学期</h3>
          </div>
          <Selector
            options={semesterOptions}
            value={selectedSemester}
            onChange={setSelectedSemester}
            className={styles.selector}
          />
        </Card>

        {/* 统计信息 */}
        <Card className={styles.statsCard}>
          <div className={styles.statsHeader}>
            <h3 className={styles.statsTitle}>学期统计</h3>
            <Button 
              size="small" 
              color="primary" 
              fill="outline"
              onClick={handleExport}
              className={styles.exportButton}
            >
              导出成绩单
            </Button>
          </div>
          <div className={styles.statsGrid}>
            <div className={styles.statItem}>
              <div className={styles.statValue}>{stats.totalCredits}</div>
              <div className={styles.statLabel}>总学分</div>
            </div>
            <div className={styles.statItem}>
              <div className={styles.statValue}>{stats.gpa}</div>
              <div className={styles.statLabel}>平均绩点</div>
            </div>
            <div className={styles.statItem}>
              <div className={styles.statValue}>{stats.averageScore}</div>
              <div className={styles.statLabel}>平均分</div>
            </div>
          </div>
        </Card>

        {/* 成绩列表 */}
        <div className={styles.gradesList}>
          {currentGrades.length > 0 ? (
            currentGrades.map((grade) => (
              <Card key={grade.id} className={styles.gradeCard}>
                <div className={styles.gradeHeader}>
                  <div className={styles.courseInfo}>
                    <h4 className={styles.courseName}>{grade.courseName}</h4>
                    <div className={styles.courseDetails}>
                      <span className={styles.courseCode}>{grade.courseCode}</span>
                      <span className={styles.courseType}>{grade.courseType}</span>
                      <span className={styles.teacher}>👨‍🏫 {grade.teacher}</span>
                    </div>
                  </div>
                  <div className={styles.scoreSection}>
                    <div 
                      className={styles.score}
                      style={{ color: getScoreColor(grade.score) }}
                    >
                      {grade.score}
                    </div>
                    <div className={styles.gradeLevel}>
                      {getGradeLevel(grade.score)}
                    </div>
                  </div>
                </div>
                <div className={styles.gradeFooter}>
                  <div className={styles.gradeDetail}>
                    <span className={styles.detailLabel}>学分:</span>
                    <span className={styles.detailValue}>{grade.credit}</span>
                  </div>
                  <div className={styles.gradeDetail}>
                    <span className={styles.detailLabel}>绩点:</span>
                    <span className={styles.detailValue}>{grade.gradePoint}</span>
                  </div>
                  <div className={styles.gradeDetail}>
                    <span className={styles.detailLabel}>状态:</span>
                    <span className={styles.statusValue}>{grade.status}</span>
                  </div>
                </div>
              </Card>
            ))
          ) : (
            <div className={styles.emptyState}>
              <div className={styles.emptyIcon}>📊</div>
              <div className={styles.emptyText}>暂无成绩数据</div>
              <div className={styles.emptySubtext}>请选择其他学期或联系教务处</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default GradeQuery;